<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="896" @ok="handleSubmit">
      <BasicForm @register="registerForm"/>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../ShCommoditySpecification.data';
    import {saveOrUpdate} from '../ShCommoditySpecification.api';
    import {list as listCommodity} from "/@/views/shop/commodity/ShCommodity.api"
    import {list as listSpecifications} from '/@/views/shop/specification/ShSpecification.api';
    import {queryById,queryItemsById} from "/@/views/shop/specification/ShSpecification.api";
    import {useMessage} from "@/hooks/web/useMessage";
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const { createMessage, createConfirm } = useMessage();
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate,appendSchemaByField,updateSchema,removeSchemaByFiled}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    const specifications = ref();
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;

        updateSchema({field:"commodityId", component: 'JSearchSelect',componentProps:{
            pageSize:3,
            async:true,dict:"sh_commodity,name,id",onChange:changeCommodity}})
        specifications.value="[]";

        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
          specifications.value = data.record.specifications;
          changeCommodity(data.record.commodityId);
        }

        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    const rec = ref();

    const setSpecifications = ()=>{
      let sps = JSON.parse(specifications.value);
      for(let k = 0;k<sps.length;k++){
        let sk = sps[k];
        let val = eval("({sp"+sk.code+":'"+sk.value+"'})");
        console.log(val);
        setFieldsValue(val);
      }
    }

    const changeCommodity = async (e)=>{
      let arr = [];
      console.log(e);
      if(!e){
        removeSchemaByFileds();
        return;
      }
      let param = {commodityId: e};
      let res = await listSpecifications(param);
      console.log(res)
      if(res?.records?.length>0){
          removeSchemaByFileds()

          for(let i = 0;i<res.records.length;i++){
            let res2 = await queryItemsById({id:res.records[i].id});
            console.log(res2)
            let ops = [];
            if(res2.itemList){
              for(let j = 0;j<res2.itemList.length;j++){
                ops.push({label:res2.itemList[j].name,value:res2.itemList[j].id});
              }
            }
            let t = {code:res.records[i].id,value:""};
            arr.push(t);

            console.log(ops)
            appendSchemaByField({label:res2.name,field:"sp"+res.records[i].id ,component:"Select",componentProps:{options:ops},
            },"commodityId");
          }
        setSpecifications();
      }else{
        removeSchemaByFileds();
      }
      rec.value =arr;
      console.log(formSchema)

    };
    function removeSchemaByFileds(){

      if(!rec.value)
        return;

      for(let i = 0;i<rec.value.length;i++){
        removeSchemaByFiled("sp"+rec.value[i].code);
      }
    }

    //表单提交事件
    async function handleSubmit(v) {
        try {


            let values = await validate();
            console.log(values)
          console.log(rec.value)
            for(let i = 0;i<rec.value.length;i++){
                let code = rec.value[i].code;
                console.log(code)
                let val = eval("(values.sp"+code+")")
                console.log(val);
                rec.value[i].value = val;
            }

            values.specifications = JSON.stringify(rec.value);

            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
